package middleware

import (
	"net/http"
	"strings"

	"backend-api/config"

	"github.com/gin-gonic/gin"
)

// CORSMiddleware 跨域中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		cfg := config.GlobalConfig.CORS

		// 设置允许的源
		origin := c.Request.Header.Get("Origin")
		if isAllowedOrigin(origin, cfg.AllowOrigins) {
			c.Header("Access-Control-Allow-Origin", origin)
		} else if len(cfg.AllowOrigins) > 0 && cfg.AllowOrigins[0] == "*" {
			c.Header("Access-Control-Allow-Origin", "*")
		}

		// 设置允许的方法
		c.Header("Access-Control-Allow-Methods", strings.Join(cfg.AllowMethods, ", "))

		// 设置允许的头部
		c.Header("Access-Control-Allow-Headers", strings.Join(cfg.AllowHeaders, ", "))

		// 设置暴露的头部
		if len(cfg.ExposeHeaders) > 0 {
			c.Header("Access-Control-Expose-Headers", strings.Join(cfg.ExposeHeaders, ", "))
		}

		// 设置是否允许凭证
		if cfg.AllowCredentials {
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		// 设置预检请求的缓存时间
		if cfg.MaxAge > 0 {
			c.Header("Access-Control-Max-Age", cfg.MaxAge.String())
		}

		// 处理预检请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}

// isAllowedOrigin 检查源是否被允许
func isAllowedOrigin(origin string, allowedOrigins []string) bool {
	for _, allowedOrigin := range allowedOrigins {
		if allowedOrigin == "*" || allowedOrigin == origin {
			return true
		}
	}
	return false
}